//
//  WQCalendarGridView.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-25.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "WQCalendarGridView.h"
#import "WQCalendarTileView.h"
#import "NSDate+WQCalendarLogic.h"
#import "WQCalendarCellData.h"
#import "WQCalendarTeacherCellView.h"

@interface WQCalendarGridView (){
    NSDate *today;
}

@property (strong, nonatomic)NSMutableArray *calendarDays;
@property (strong, nonatomic)NSMutableArray *daysInPreviousMonth;
@property (strong, nonatomic)NSMutableArray *daysInCurrentMonth;
@property (strong, nonatomic)NSMutableArray *daysInFollowingMonth;

@property(strong, nonatomic)NSMutableArray *gridViewCell;


@property(weak, nonatomic)WQCalendarTileView *selectedCellView;
@end

@implementation WQCalendarGridView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    NSLog(@"drawRect %@", NSStringFromCGRect(rect));
    today = [NSDate date];
    BOOL isSameMonth = [today isSameMonth:self.displayDate];
//    self.backgroundColor = [UIColor lightGrayColor];
    
    [self.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [obj removeFromSuperview];
    }];
    
    CGFloat cellSize  = (rect.size.width-6)/7;
    
    
    int rowCount = 7;
//    if (_delegate) {
//        //TODO: 计算行数
//    }else{
        rowCount = [self numberOfRowInCurrenMonth];
//    }
    CGRect frame = self.frame;
    frame.size.height = cellSize*rowCount +rowCount-1;
    self.frame = frame;
    
    /**
     *  !!!!!!!!!!!!!
     */
    _calendarDays = [[NSMutableArray alloc]init];
    [self markDateArray];
    
    int colBorder = 0;
    int rowBorder = 0;
    int countPointer = 0;
    
    for (int i = 0; i<rowCount; i++) {
        
        for (int j = 0 ; j<7; j++) {
            CGRect cellFrame = CGRectMake((cellSize + colBorder)*j, (cellSize+rowBorder)*i, cellSize, cellSize);
            
            if (self.isForTeacher) {
                WQCalendarTeacherCellView *cellView;
                
                cellView = [self makeTeacherCellViewForRow:i column:j countPointer:countPointer];
                
                
                if (j==0 || j==6) {
                    cellView.isWeekEnd = YES;
                }
                cellView.frame = cellFrame;
                
                cellView.indexPath = [NSIndexPath indexPathForRow:j inSection:i];
                if (cellView.isCurrentMonthDay) {
                    UIGestureRecognizer * gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchCellAction:)];
                    [cellView addGestureRecognizer:gesture];
                }else{
                    cellView.backgroundColor = RGBACOLOR(200, 200, 200, 1);
                }
                
                [self addSubview:cellView];
                
                colBorder = 1;
                
                countPointer++;
            }else{
                WQCalendarTileView *cellView;
                
                cellView = [self makeDefultCellViewForRow:i column:j countPointer:countPointer];
                
                
                if (j==0 || j==6) {
                    cellView.isWeekEnd = YES;
                }
                cellView.frame = cellFrame;
                
                cellView.indexPath = [NSIndexPath indexPathForRow:j inSection:i];
                if (cellView.isCurrentMonthDay) {
                    UIGestureRecognizer * gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchCellAction:)];
                    [cellView addGestureRecognizer:gesture];
                }else{
                    cellView.backgroundColor = RGBACOLOR(200, 200, 200, 1);
                }
                
                [self addSubview:cellView];
                
                colBorder = 1;
                
                countPointer++;
                
                
                //mark default day
                
                if (isSameMonth && [today isSameDay:cellView.day] && cellView.isCurrentMonthDay) {
                    if (_delegate) {
                        
                        [_delegate  gridView:self didSelectAtCell:cellView];
                    }
                    [_selectedCellView setSelected:NO];
                    [cellView setSelected:YES];
                    _selectedCellView = cellView;
                }
            }
            
        }
        colBorder = 0;
        rowBorder = 1;
    }
   
    
}

- (NSUInteger)numberOfRowInCurrenMonth{

    NSUInteger dayCount = [_displayDate numberOfWeeksInCurrentMonth];
    return dayCount;
}

- (WQCalendarTileView *)makeDefultCellViewForRow:(NSUInteger)i column:(NSUInteger)j countPointer:(NSUInteger)countPointer{
    
    WQCalendarTileView *cellView = [[WQCalendarTileView alloc]init];
    cellView.backgroundColor = [UIColor whiteColor];
    cellView.tag = 100+countPointer;
    
    
    //处理过空白列就不用了
    if (countPointer< _calendarDays.count) {
        WQCalendarCellData *data =_calendarDays[countPointer];
        cellView.day = [data.date dayStringInMonth];
        cellView.isCurrentMonthDay = data.enable;
        
        if (_checkOnData) {
            [_checkOnData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSString *dateString = obj[@"checkOnDate"];
                if ([dateString isEqualToString:[data.date stringWithYYY_MM_dd]]) {
                    cellView.checkOnData = obj;
                    if (![obj[@"checkInTime"]isEqualToString:@""]) {
                        cellView.isShowCheckInImage = YES;
                    }
                    if (![obj[@"checkOutTime"]isEqualToString:@""]) {
                        cellView.isShowCheckOutImage = YES;
                    }

                    *stop = YES;
                }
            }];
        }
    }
    
    
    
    
//    cellView.isShowCheckInImage = YES;
//    cellView.isShowCheckOutImage = YES;
//    cellView.day = @"29";
    return cellView;
}

- (WQCalendarTeacherCellView *)makeTeacherCellViewForRow:(NSUInteger)i column:(NSUInteger)j countPointer:(NSUInteger)countPointer{
    
    WQCalendarTeacherCellView *cellView = [[WQCalendarTeacherCellView alloc]init];
    cellView.backgroundColor = [UIColor whiteColor];
    cellView.tag = 100+countPointer;
    
    
    //处理过空白列就不用了
    if (countPointer< _calendarDays.count) {
        WQCalendarCellData *data =_calendarDays[countPointer];
        cellView.day = [data.date dayStringInMonth];
        cellView.isCurrentMonthDay = data.enable;
        
        if (self.checkOnData) {
            [self.checkOnData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSString *dateString = obj[@"markDate"];
                if ([dateString isEqualToString:[data.date stringWithYYY_MM_dd]]) {
                    cellView.isMark = YES;
                    *stop = YES;
                }
            }];
        }
    }
    
    
    
    
    //    cellView.isShowCheckInImage = YES;
    //    cellView.isShowCheckOutImage = YES;
    //    cellView.day = @"29";
    return cellView;
}

- (void)touchCellAction:(UIGestureRecognizer *)sender{
    NSLog( @"touchCellAction %@", [sender.view valueForKey:@"indexPath"]);
    WQCalendarTileView *cellView =(WQCalendarTileView *) sender.view;
    if (_delegate) {
        
        [_delegate  gridView:self didSelectAtCell:cellView];
    }
    [_selectedCellView setSelected:NO];
    [cellView setSelected:YES];
    _selectedCellView = cellView;
}



- (void)markDateArray{
    [self calculateDaysInPreviousMonthWithDate:_displayDate];
    [self calculateDaysInCurrentMonthWithDate:_displayDate];
    [self calculateDaysInFollowingMonthWithDate:_displayDate];
//    
//    NSLog(@"previousMonth");
//    [_daysInPreviousMonth enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        NSLog(@"datetime = %@", obj);
//    }];
//    NSLog(@"currentMonth");
//    [_daysInCurrentMonth enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        NSLog(@"datetime = %@", obj);
//    }];
//    NSLog(@"followingMonth");
//    [_daysInFollowingMonth enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        NSLog(@"datetime = %@", obj);
//    }];
}

- (void)calculateDaysInPreviousMonthWithDate:(NSDate *)date
{
    NSUInteger weeklyOrdinality = [[date firstDayOfCurrentMonth] weeklyOrdinality];
    NSDate *dayInThePreviousMonth = [date dayInThePreviousMonth];
    
    NSUInteger daysCount = [dayInThePreviousMonth numberOfDaysInCurrentMonth];
    NSUInteger partialDaysCount = weeklyOrdinality - 1;
    
    NSDateComponents *components = [dayInThePreviousMonth YMDComponents];
    
    self.daysInPreviousMonth = [NSMutableArray array];
    for (int i = daysCount - partialDaysCount + 1; i < daysCount + 1; ++i) {
        NSDate *calendarDay = [NSDate calendarDayWithYear:components.year month:components.month day:i];
        WQCalendarCellData *data = [[WQCalendarCellData alloc]init];
        data.date = calendarDay;
        data.enable = NO;
        
        [self.daysInPreviousMonth addObject:data];
        [self.calendarDays addObject:data];
    }
}

- (void)calculateDaysInCurrentMonthWithDate:(NSDate *)date
{
    NSUInteger daysCount = [date numberOfDaysInCurrentMonth];
    NSDateComponents *components = [date YMDComponents];
    
    self.daysInCurrentMonth = [NSMutableArray arrayWithCapacity:daysCount];
    for (int i = 1; i < daysCount + 1; ++i) {
        NSDate *calendarDay = [NSDate calendarDayWithYear:components.year month:components.month day:i];

        WQCalendarCellData *data = [[WQCalendarCellData alloc]init];
        data.date = calendarDay;
        data.enable = YES;
        
        [self.daysInCurrentMonth addObject:data];
        [self.calendarDays addObject:data];
    }
}

- (void)calculateDaysInFollowingMonthWithDate:(NSDate *)date
{
    NSUInteger weeklyOrdinality = [[date lastDayOfCurrentMonth] weeklyOrdinality];
    if (weeklyOrdinality == 7) return ;
    
    NSUInteger partialDaysCount = 7 - weeklyOrdinality;
    NSDateComponents *components = [[date dayInTheFollowingMonth] YMDComponents];
    
    self.daysInFollowingMonth = [NSMutableArray arrayWithCapacity:partialDaysCount];
    for (int i = 1; i < partialDaysCount + 1; ++i) {
        NSDate *calendarDay = [NSDate calendarDayWithYear:components.year month:components.month day:i];
        
        WQCalendarCellData *data = [[WQCalendarCellData alloc]init];
        data.date = calendarDay;
        data.enable = NO;
        
        [self.daysInFollowingMonth addObject:data];
        [self.calendarDays addObject:data];
    }
}



- (void)reloadData{
    [self setNeedsDisplay];
}
@end
